// pages/order/order.js
var that,
  api = new (require('../../utils/api.js')),
  headimg = api.getimgurl(),
  app = getApp(),
  util = new (require('../../utils/util.js')),
  tabbars = ['ALL', 'NO_PAY', 'PAY_SUCCESS', 'SHIPPED', 'RECEIVED', 'SOLVING', 'SOLVED','CANCELED'];
function getstatecontent(state) {
  if (state == 'PAY_SUCCESS') return '待发货';
  if (state == 'NO_PAY') return '待付款';
  if (state == 'CANCELED') return '已取消';
  if (state == 'SHIPPED') return '已发货';
  if (state == 'RECEIVED') return '待还书';
  if (state == 'SHOPSHIPPED') return '店家待收货';
  if (state == 'SOLVING') return '正在处理退款';
  if (state == 'SOLVED') return '退款已处理';
  return '';
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pagesize: 20,
    currentpage: 1,
    list: [],
    start:0,
    headimg,
    isappointment:!1,
    days:[
      {
        id:-1,
        day:'请选择日期'
      },
      {
        id:0,
        day:'今天'
      },
      {
        id:1,
        day:'明天'
      },
      {
        id:2,
        day:'后天'
      },
    ],
    times:[
      {
        id:-1,
        time:'请选择时间',
      },
      {
        id:0,
        time:'9:00-10:00',
      },
      {
        id:1,
        time:'10:00-11:00',
      },
      {
        id:2,
    
        time:'11:00-12:00',
      },
      {
        id:3,
        time:'12:00-13:00',
        
      },
      {
        id:4,
        time:'13:00-14:00',
   
      },
      {
        id:5,
        time:'14:00-15:00',
   
      },
      // {
      //   id:6,
      //   time:'14:00-15:00',
        
      // },
      {
        id:7,
        time:'15:00-16:00',
        
      },
      {
        id:8,
        time:'16:00-17:00',
        
      },
      {
        id:9,
        time:'17:00-18:00',
      },
      {
        id:10,
        time:'18:00-19:00',
      },
    ],
    backdatetime:'',
    backdate:'请选择日期',
    ordernums:'',
    timeselect:-1,
    dayselect:-1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this
    // this.getwindowwidth();
    // console.log(options,'optionsoptionsoptions');
    // if(options.o){
    //   let tabindex = options.o;
    //   this.setData({tabindex});
    //   this.getlist(tabindex,0);
    // }
    that.getdata()
    
  },

 

  getdata(){
    api.accountlist(res=>{
      let {list} = res.data
        list.forEach(x=>{
          x['deadline']=util.formatDate(new Date(x.deadline))
        })
        that.setData({list})
    })
  },
  formsubmit(e) {
    api.gatherformid(e, res => {

    })
  },
  addcart(e){
    let {list} = this.data,{index} = e.target.dataset,
    goodsid = list[index].goodsid;
    
    api.addcart({ goodsid }, res => {
      if (res.data.issuccess == 1) {
        wx.showToast({
          title: '添加成功',
        })
      }
    });
  },
  getwindowwidth(){
    var singleNavWidth = wx.getSystemInfoSync().windowWidth / 3;
    this.setData({singleNavWidth});
  },
  tabtap(e){
    let { index } = e.target.dataset, { tabindex, singleNavWidth} = this.data;
    if (tabindex == index) {
      console.log("tabindex","index");
      return;
    } 
    this.setData({ tabindex: index, currentpage: 1,list:[]},()=>{
      that.getlist(index,0);
    });
  },
  tomain(e) {
    wx.switchTab({
      url: '../main/main',
    })
  },
  tologistics(e){
    console.log(e,'tologisticstologisticstologistics')
    let{lcode}=e.currentTarget.dataset
    wx.navigateTo({
      url: '../logistics/logistics?lcode='+lcode,
    })
  },
  getlist(tabindex,start) {
    let {pagesize,singleNavWidth,list} = this.data;
    this.setData({ clist: [], navScrollLeft: ((tabindex - 1) * singleNavWidth)});
    wx.showLoading({
      title: '加载中',
    })
    api.getorderlist({state:tabbars[tabindex],pagesize,start}, res => {
      wx.hideLoading();
      if (res.data.issuccess == 1) {
       
        console.log("index",res.data.data);
        if (res.data.data.length > 0) {
          console.log(res.data.data);
          res.data.data.forEach((x,i) => {
            console.log(x,'xxxxxxxxx');
            
            x.borrowDate = util.formatDate(new Date(x.item.borrowDate));
            x.backDate = util.formatDate(new Date(x.item.backDate));
            x.createDate = util.formatTime(new Date(x.item.createDate));
            x.payDate = util.formatDate(new Date(x.item.payDate));
            x.statecontent = getstatecontent(x.item.state);
            x.total = x.item.total/100;
            x.deposit = x.item.deposit/100;
            if(x.books){
              x.books.forEach((y,z)=>{
                if (y.goodsimg.indexOf("http")== -1) {
                  y.thumbPicPath = headimg + y.goodsimg;
                }else{
                  y.thumbPicPath=y.goodsimg
                }
              })
            }
            list.push(x)
            that.setData({list,reachbtm:list.length==res.data.total})
          })
          if(list.length==0){

            this.setData({length:0});
          }
          this.setData({ tabindex,list },()=>{
            wx.hideLoading()
          })
        }else{
          let list = []
          that.setData({list})
        }
      }
    })
  },
  cancelorder(e){
    let {index} = e.target.dataset,ordernumber = this.data.list[index].ordernum;
    api.cancelorder({ordernumber},res=>{
      if(res.data.issuccess==1){
        wx.showToast({
          title: '已取消',
        })
        let {tabindex} = this.data;
        this.setData({  currentpage: 1, list: [] },()=>{
          that.getlist(tabindex,0);
        });
      }
    });
  },
  pay(e) {
    let { index } = e.target.dataset, { tabindex, list } = this.data, { ordernum, goodsid } = list[index],
      cost = this.data.list[index].total * 100;
    api.prepay({ ordernumber: ordernum, total: cost }, res => {
      // console.log(res, 'resrespay')
      if (res.succ == 1) {
        api.afterpaysucc({ ordernumber: ordernum, cost, goodsid }, res => {
          if (res.data.issuccess == 1) {
            that.setData({ currentpage: 1, list: []},()=>{
              that.getlist(tabindex,0);
            })
          }
        })
      } else {
        // this.getlist(tabindex, 0);
      }
    })
  },
  findbooksbyids(ids,list,i) {
    api.getbooks({ ids }, res => {
      if (res.data.issuccess == 1) {
        console.log(res,'getbooksgetbooksgetbooksgetbooks')
        this.formatdata(res.data.data,list,i);
      }
    });
  },

  delaccount(e){
    wx.showModal({
      title: '提示',
      content: '确定要删除吗',
      complete: (res) => {
    
        if (res.confirm) {
          let{id}=e.currentTarget.dataset;
          api.删除用户(id,res=>{
            if(res.data.issuccess==1){
              that.getdata()
            }else{
              wx.showToast({
                title: res.data.msg,
              }) 
            }
          })
        }
      }
    })
    
  },

  changedate(e){
    let{id}=e.currentTarget.dataset,{value} = e.detail
    
    api.修改到期时间({id,dl:new Date(value).getTime()/1000},res=>{
      if(res.data.issuccess==1){
        that.getdata()
      }else{
        wx.showToast({
          title: res.data.msg,
        }) 
      }
    })

  },


  formatdata(books,clist,i) {
  
    books.forEach((x, i) => {
      console.log(x,'thumbPicPaththumbPicPaththumbPicPath')
      if (x.thumbPicPath.indexOf("http")== -1) {
        x.thumbPicPath = headimg + x.thumbPicPath;
      }
      x.detaillist = x.detaillist.split(',');
      x.labels = x.labels.split(',');
      if (x.detaillist.length > 0) {
        x.detaillist.forEach((y, i) => {
          if (y.indexOf("http") == -1) {
            x.detaillist[i] = headimg + x.detaillist[i];
          }
        });
      }
    });

    clist[i].books = books;
    if(clist.length-1==i){
      let length = clist.length, { list } = this.data;
      list = list.concat(clist);
      this.setData({ list, length});
      wx.hideLoading();
    }  
  },
  toappointment(e){
    let {isappointment,ordernums} =this.data,{ordernum}=e.currentTarget.dataset
    this.setData({isappointment:!0,ordernums:ordernum})
  },
  modsend(){
    let {isappointment} =this.data
    this.setData({isappointment:!1})
  },
  todetail(e){
    let {index} = e.currentTarget.dataset;
    wx.navigateTo({
      url: '../orderdetail/orderdetail?i='+index,
    })
  },
  getdate(e){
    let {id} =e.currentTarget.dataset,{dayselect,backdate}=this.data
    this.setData({dayselect:id})
    console.log(id,'idddd')
    if(id==0){
      //今天的时间
      var day2 = new Date();
      day2.setTime(day2.getTime());
       backdate = day2.getFullYear()+"-" + (day2.getMonth()+1) + "-" + day2.getDate();
      this.setData({backdate})
      console.log(backdate,'backdatebackdatebackdate')
    }else if(id==1){
       //明天的时间
      var day3 = new Date();
      day3.setTime(day3.getTime()+24*60*60*1000);
       backdate = day3.getFullYear()+"-" + (day3.getMonth()+1) + "-" + day3.getDate();
      this.setData({backdate})
      console.log(backdate,'backdatebackdatebackdate')
    }else if(id==2){
      var day4 = new Date();
      day4.setTime(day4.getTime()+(24*60*60*1000)*2);
       backdate = day4.getFullYear()+"-" + (day4.getMonth()+1) + "-" + day4.getDate();
      this.setData({backdate})
      console.log(backdate,'backdatebackdatebackdate')
    }  
   
},
gettime(e){
  console.log(e,'eeee')
  let {time,id} = e.currentTarget.dataset,{backdatetime,dayselect,timeselect,backdate}=this.data,myDate = new Date();
  if(backdate=='请选择日期'){
    wx.showToast({
      title: '请选择日期',
      icon:'none'
    })
    return 
  }else{
    let stime =new Date(myDate).getTime();
    console.log(stime,'stime');
    let newtime = time.substring(0,time.length-6)
    console.log(newtime,'newtime');
    let times = backdate + ' ' + newtime
    console.log(times,'times');
    let etime = new Date(times).getTime();
    console.log(etime,'etime');
    let timenum=etime-stime 
    console.log(timenum,'timenum');
    let hours = parseInt(timenum / 1000 / 60 / 60 % 24, 10);
    console.log(hours,'hours');
    if(hours<5&&dayselect==0){
      wx.showModal({
        title: '提示',
        content: '请提前五个小时预约',
      })
    }else{
      this.setData({backdatetime:time,timeselect:id})
    }  
  }
},
yes(e){
  let {backdate,backdatetime,ordernums,start,tabindex,dayselect,timeselect}=this.data
  console.log(backdate,backdatetime,ordernums,'yesyesyesyes')
  if(dayselect==-1||timeselect==-1){
    wx.showToast({
      title: '请选择时间',
      icon: "none",
    })
    return false
  }
    api.setbackdate({ ordernumber:ordernums,backdate, backdatetime}, res => {
      if (res.data.issuccess == 1) {
        this.setData({isappointment:!1},()=>{
          wx.showModal({
            title: '提示',
            content:'预约成功',
            showCancel:!1,
            success:function(res1){
              if (res1.confirm) {
                this.setData({list:[]},()=>{
                  that.getlist(that.data.tabindex,start)
                })
              }
            }
          })
          
        })
      }
    });
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // let { pagesize, currentpage, start, length, tabindex } = this.data;
    // console.log(length,pagesize,"pagesize");
    // if (length != pagesize) {
    //   wx.showToast({
    //     icon: "none",
    //     title: '再怎么扯也没有了',
    //   })
    //   return;
    // }
    // start = pagesize * currentpage; currentpage = currentpage + 1;
    // this.setData({ start, currentpage });
    // this.getlist(tabindex,start);

    // let { reachbtm,start, pagesize,tabindex} = this.data;
    // if (!reachbtm) {
    //   that.setData({ start: start + pagesize }, () => {
    //     this.getlist(tabindex,start);
    //   })
    // }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.logininfo.appletname,
      path: `pages/listen/listen?share=`+app.logininfo.userid,
    }
  }
})